package com.sensetime.stlivenesslibrary.ui;

import java.io.File;

import com.sensetime.stlivenesslibrary.ui.LivenessNoteActivity;
import com.sensetime.stlivenesslibrary.R;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.sensetime.stlivenesslibrary.ui.LivenessActivity;

public class LivenessNoteActivity extends Activity {
	private Button startBtn;
	private Bundle bundle;
//	private String SDCARD_STORAGE_PATH = Environment
//			.getExternalStorageDirectory().getAbsolutePath()
//			+ File.separator
//			+ "liveness"+File.separator;
	private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.linkface_activity_liveness_note);
		bundle = getIntent().getExtras();
		startBtn = (Button) findViewById(R.id.start_button);
//		File livenessFolder = new File(SDCARD_STORAGE_PATH);
//        if (!livenessFolder.exists()) {
//            livenessFolder.mkdirs();
//        }
        //开始检测之前请删除文件夹下保留的文件
//        deleteFiles(SDCARD_STORAGE_PATH);
		startBtn.setOnClickListener(new View.OnClickListener() {

			@SuppressLint("NewApi")
            @Override
			public void onClick(View arg0) {
				if(isMarshmallow()) {
					if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
							!= PackageManager.PERMISSION_GRANTED) {
						if (shouldShowRequestPermissionRationale(
								Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
							// Provide an additional rationale to the user if the permission was not granted
							// and the user would benefit from additional context for the use of the permission.
						}
						// Request the permission. The result will be received in onRequestPermissionResult()
						requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
								PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
					} else {
						// Permission is already available, start camera preview
						startLivenessDetect();
					}
				} else {
					startLivenessDetect();
				}
			}
		});
	}

	private void startLivenessDetect() {
		Intent intent = new Intent();
		intent.setClass(LivenessNoteActivity.this, LivenessActivity.class);
//		intent.putExtra(LivenessActivity.EXTRA_RESULT_PATH, SDCARD_STORAGE_PATH);
		intent.putExtra(LivenessActivity.SEQUENCE_JSON,
				bundle.getString("sequence_json"));
		// 声音提示开关
		intent.putExtra(LivenessActivity.SOUND_NOTICE, bundle.getBoolean(LivenessActivity.SOUND_NOTICE));
		intent.putExtras(bundle);
		startActivityForResult(intent, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
		// 0: blink 1: mouth 2:headyaw 3:headnod
		    for (int i=0; i < 4; ++i) {
		        int motion = data.getIntExtra("motion" + i, -1);
		        byte[] image = data.getByteArrayExtra("image" + i);
		    }
			Toast.makeText(this, "活体检测成功", Toast.LENGTH_SHORT).show();
		default:
			break;
		}
	}

	public static void deleteFiles(String folderPath) {
		File dir = new File(folderPath);
		if (dir == null || !dir.exists() || !dir.isDirectory() || dir.listFiles() == null)
			return;
		for (File file : dir.listFiles()) {
			if (file.isFile())
				file.delete();
		}
	}

	private static boolean isMarshmallow() {
		return Build.VERSION.SDK_INT >= 23;
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions,
										   int[] grantResults) {

		if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE) {
			// Request for WRITE_EXTERNAL_STORAGE permission.
			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				//TODO
				// Permission has been granted. Start Liveness Detect.
				startLivenessDetect();
			} else {
				// Permission request was denied.
				Toast.makeText(this, "WRITE_EXTERNAL_STORAGE 权限被拒绝, 不能启动活体检测.", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}
}
